package com.wbpay.sdk.dlg;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Selection;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.wbpay.sdk.framework.IUserFunction;
import com.wbpay.sdk.utils.Log;
import com.wbpay.sdk.utils.ParamsValidator;
import com.wbpay.sdk.utils.SMSCountDownTimer;
import com.wbpay.sdk.utils.Utils;
import com.wbpay.sdk.widget.ClearTextWatcher;

/**
 * Created by ck01- on 2017/7/5.
 */

public class RegisterDialog extends Dialog implements CompoundButton.OnCheckedChangeListener, View.OnClickListener, RadioGroup.OnCheckedChangeListener {

    private LinearLayout mCurrentCellphoneLinear;
    private TextView mCurrentCellphoneText;// 显示本机号码
    private CheckBox mInputCellphoneCheck;// 是否使用其他手机号注册
    private EditText mAccountEdit;// 手机号/用户名输入框
    private EditText mPasswordEdit;// 密码输入框
    private CheckBox mShowPasswordCheck;// 显示密码
    private Button mRegisterButton;// 注册按钮
    private CheckBox mProtocolCheck;// 久游注册协议
    private ImageButton mClearCellphoneButton;
    private ImageButton mClearPasswordButton;
    private LinearLayout mCellphoneLinear;
    private TextView mProtocolText;
    private RadioGroup mRadioRegisterType;
    private IUserFunction mUserFunction;
    private View mCaptchaLayout;
    private TextView mFetchCaptcha;
    private EditText mCaptchaEdit;
    private SMSCountDownTimer mSMSCountDownTimer;

    public RegisterDialog(Context context, IUserFunction f) {
        super(context, android.R.style.Theme_DeviceDefault_NoActionBar);
        mUserFunction = f;
        setCanceledOnTouchOutside(false);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(Utils.getLayoutId(getContext(), "jy_dialog_register"));
        initView();
        initData();
        updateWindow();
    }

    private void updateWindow() {
    }

    private void initView() {
        mCurrentCellphoneLinear = (LinearLayout) findViewById(Utils.getId(getContext(), "linear_current_cellphone"));
        mCurrentCellphoneText = (TextView) findViewById(Utils.getId(getContext(), "text_current_cellphone"));
        mInputCellphoneCheck = (CheckBox) findViewById(Utils.getId(
                getContext(), "check_input_cellphone"));
        mAccountEdit = (EditText) findViewById(Utils.getId(
                getContext(), "edit_account"));
        mProtocolText = (TextView) findViewById(Utils.getId(
                getContext(), "text_protocol"));
        mPasswordEdit = (EditText) findViewById(Utils.getId(
                getContext(), "edit_password"));
        mShowPasswordCheck = (CheckBox) findViewById(Utils.getId(
                getContext(), "check_show_password"));
        mRegisterButton = (Button) findViewById(Utils.getId(
                getContext(), "btn_register"));
        mProtocolCheck = (CheckBox) findViewById(Utils.getId(
                getContext(), "check_protocol"));
        mClearCellphoneButton = (ImageButton) findViewById(Utils
                .getId(getContext(), "clear_edit_account"));
        mClearPasswordButton = (ImageButton) findViewById(Utils.getId(
                getContext(), "clear_edit_password"));
        mCellphoneLinear = (LinearLayout) findViewById(Utils.getId(
                getContext(), "linear_account"));

        mCaptchaLayout = findViewById(Utils.getId(
                getContext(), "linear_captcha"));
        mFetchCaptcha = (TextView) findViewById(Utils.getId(
                getContext(), "fetch_captcha"));
        mCaptchaEdit = (EditText) findViewById(Utils.getId(
                getContext(), "edit_captcha"));

        mRadioRegisterType = (RadioGroup) findViewById(Utils.getId(getContext(), "register_type"));
        mRadioRegisterType.setOnCheckedChangeListener(this);

        View back = findViewById(Utils.getId(getContext(), "btn_title_back"));
        back.setOnClickListener(this);

        mShowPasswordCheck.setOnCheckedChangeListener(this);
        mProtocolCheck.setOnCheckedChangeListener(this);
        mRegisterButton.setOnClickListener(this);
        mInputCellphoneCheck.setOnCheckedChangeListener(this);
        mClearPasswordButton.setOnClickListener(this);
        mClearCellphoneButton.setOnClickListener(this);
        mProtocolText.setOnClickListener(this);
        mFetchCaptcha.setOnClickListener(this);


        mClearCellphoneButton.setVisibility(TextUtils.isEmpty(mAccountEdit
                .getText()) ? View.GONE : View.VISIBLE);
        mClearPasswordButton.setVisibility(TextUtils.isEmpty(mPasswordEdit
                .getText()) ? View.GONE : View.VISIBLE);
        mAccountEdit.addTextChangedListener(new ClearTextWatcher(
                mClearCellphoneButton));
        mPasswordEdit.addTextChangedListener(new ClearTextWatcher(
                mClearPasswordButton));
    }

    private void initData() {
        setCountDown(null);
        initCellphoneData();
    }

    private void initCellphoneData() {
        showCellphoneRegisterView();
        String cellphone = getCellphoneNumber();
        autoFill(cellphone);
    }

    private void initUsernameData() {
        showUsernameRegisterView();
    }

    private String getCellphoneNumber() {
        TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
        String cellphoneNumber = telephonyManager.getLine1Number();
        if (!TextUtils.isEmpty(cellphoneNumber))
            cellphoneNumber = cellphoneNumber.replaceAll("\\u002B86", "");
        try {
            ParamsValidator.checkTelphone(cellphoneNumber);
        } catch (Exception e) {
            cellphoneNumber = null;
        }
        return cellphoneNumber;
    }

    private void autoFill(String cellphone) {
        boolean isEmpty = TextUtils.isEmpty(cellphone);
        mCurrentCellphoneLinear.setVisibility(isEmpty ? View.GONE : View.VISIBLE);
        mCellphoneLinear.setVisibility(isEmpty ? View.VISIBLE : View.GONE);
        mCurrentCellphoneText.setText(isEmpty ? "" : cellphone);
        mInputCellphoneCheck.setChecked(isEmpty);
    }

    private void showCellphoneRegisterView() {
        mCurrentCellphoneLinear.setVisibility(View.VISIBLE);
        mAccountEdit.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        mAccountEdit.setHint(Utils.getStringId(getContext(), "jy_activity_register_cellphone"));
        mAccountEdit.setText(null);
        mAccountEdit.setError(null);
        mPasswordEdit.setText(null);
        mPasswordEdit.setError(null);
        mCaptchaEdit.setError(null);
        mCaptchaEdit.setText(null);
        mCaptchaLayout.setVisibility(View.VISIBLE);
        mAccountEdit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
    }

    private void showUsernameRegisterView() {
        mCurrentCellphoneLinear.setVisibility(View.GONE);
        mCellphoneLinear.setVisibility(View.VISIBLE);
        mAccountEdit.setVisibility(View.VISIBLE);
        mAccountEdit.setInputType(EditorInfo.TYPE_CLASS_TEXT);
        mAccountEdit.setHint(Utils.getStringId(getContext(), "jy_activity_register_username"));
        mAccountEdit.setText(null);
        mAccountEdit.setError(null);
        mPasswordEdit.setError(null);
        mPasswordEdit.setText(null);
        mCaptchaEdit.setError(null);
        mCaptchaEdit.setText(null);
        mCaptchaLayout.setVisibility(View.GONE);
        mAccountEdit.setFilters(new InputFilter[]{});
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        int check_show_password = Utils.getId(getContext(), "check_show_password");// 显示/隐藏密码
        int check_protocol = Utils.getId(getContext(), "check_protocol");// 同意注册协议
        int check_input_cellphone = Utils.getId(getContext(), "check_input_cellphone");// 用户输入手机号
        if (buttonView.getId() == check_show_password) {
            int inputType = isChecked ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
            mPasswordEdit.setInputType(inputType);
            Editable etable = mPasswordEdit.getText();
            Selection.setSelection(etable, etable.length());
        }
        if (buttonView.getId() == check_protocol) {
            mRegisterButton.setEnabled(isChecked);
        }
        if (buttonView.getId() == check_input_cellphone) {
            mCellphoneLinear.setVisibility(isChecked ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        int btn_register = Utils.getId(getContext(), "btn_register");
        int text_protocol = Utils.getId(getContext(), "text_protocol");
        int clear_edit_account = Utils.getId(getContext(), "clear_edit_account");
        int clear_edit_password = Utils.getId(getContext(), "clear_edit_password");
        if (v.getId() == btn_register) {
            String account = mAccountEdit.getText().toString();
            String password = mPasswordEdit.getText().toString();
            String captcha = mCaptchaEdit.getText().toString();
            if (mRadioRegisterType.getCheckedRadioButtonId() == Utils.getId(getContext(), "register_by_cellphone")) {
                if (!mInputCellphoneCheck.isChecked()) {// 使用本机号码注册
                    account = getCellphoneNumber();
                }
                if (mUserFunction != null) {
                    mUserFunction.registerByCellphone(account, password, captcha);
                }
            } else if (mRadioRegisterType.getCheckedRadioButtonId() == Utils.getId(getContext(), "register_by_username")) {
                if (mUserFunction != null) {
                    mUserFunction.registerByUsername(account, password);
                }
            }
        } else if (v.getId() == text_protocol) {
            mUserFunction.showAgreement();
        } else if (v.getId() == clear_edit_account) {
            mAccountEdit.setText("");
            mAccountEdit.requestFocus();
            mAccountEdit.setError(null);
        } else if (v.getId() == clear_edit_password) {
            mPasswordEdit.setText("");
            mPasswordEdit.requestFocus();
            mPasswordEdit.setError(null);
        } else if (v.getId() == Utils.getId(getContext(), "btn_title_back")) {
            cancel();
        } else if (v.getId() == Utils.getId(getContext(), "fetch_captcha")) {
            Log.d(Log.TAG, "");
            if (mUserFunction != null) {
                String account = mAccountEdit.getText().toString();
                if (!mInputCellphoneCheck.isChecked()) {// 获取的手机号注册
                    account = getCellphoneNumber();
                }
                mUserFunction.fetchCaptcha(account);
            }
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == Utils.getId(getContext(), "register_by_cellphone")) { // 切换手机号码注册
            initCellphoneData();
        } else if (checkedId == Utils.getId(getContext(), "register_by_username")) { // 切换用户名注册
            initUsernameData();
        }
    }

    /**
     * 设置账户输入框的错误信息
     *
     * @param error
     */
    public void setAccountError(String error) {
        mAccountEdit.setError(error);
        mAccountEdit.requestFocus();
    }

    /**
     * 设置密码输入框的错误信息
     *
     * @param error
     */
    public void setPasswordError(String error) {
        mPasswordEdit.setError(error);
        mPasswordEdit.requestFocus();
    }

    /**
     * 设置验证码输入框的错误信息
     *
     * @param error
     */
    public void setCaptchaError(String error) {
        mCaptchaEdit.setError(error);
        mCaptchaEdit.requestFocus();
    }

    public void setCountDown(Integer millisInFuture) {
        if (millisInFuture == null) {
            long sendtime = Utils.getLong(getContext(), "register_captcha_start");
            long interval = System.currentTimeMillis() - sendtime;
            if (0 < interval && interval < 60000)
                millisInFuture = (int) (60000 - interval);
            else
                return;
        }
        mSMSCountDownTimer = new SMSCountDownTimer(millisInFuture, 1000, getContext(), mFetchCaptcha);
        mSMSCountDownTimer.start();
    }

    public void setLastSmsCaptchaTime() {
        Utils.putLong(getContext(), "register_captcha_start", System.currentTimeMillis());
    }
}
